import 'package:fig/sqlite/sql_manager.dart';
import 'package:sqflite_common/sqlite_api.dart';

class TableMediaArea extends TableBase {
  // 表名
  final String tableName = 'media_area';
  static final String columnName = "name";

  Future<void> insertAllWithMediaId(int mediaId, String areas, {Database database}) async {
    if (database == null) {
      database = await SqlManager.getCurrentDatabase();
    }

    if (areas == null || areas == "") {
      return;
    }

    var areaList = areas.split(',');
    for (String area in areaList) {
      if (area == null || area == "") {
        continue;
      }
      final areaId = await install(mediaId, area, database: database);
      installMap(mediaId, areaId, database: database);
    }
  }

  // 保存演员信息
  Future<int> install(int mediaId, String area, {Database database}) async {
    var existAreaList = await database.query(tableName, where: '$columnName=?', whereArgs: [area]);
    var areaId = 0;
    if (existAreaList.length == 0) {
      areaId = await database.insert(tableName, {
        '$columnName': area,
        '${TableBase.columnCreateTime}': DateTime.now().millisecondsSinceEpoch,
      });
    } else {
      areaId = existAreaList[0]['${TableBase.columnId}'];
    }
    return areaId;
  }

  // 保存影视关联信息
  Future<void> installMap(int mediaId, int areaId, {Database database}) async {
    var existAreaMapList = await database.query(
      TableMediaAreaMap.tableName,
      where: '${TableMediaAreaMap.columnMediaId}=? and ${TableMediaAreaMap.columnAreaId}=?',
      whereArgs: [mediaId, areaId],
    );

    if (existAreaMapList.length == 0) {
      database.insert(TableMediaAreaMap.tableName, {
        '${TableMediaAreaMap.columnMediaId}': mediaId,
        '${TableMediaAreaMap.columnAreaId}': areaId,
        '${TableBase.columnCreateTime}': DateTime.now().millisecondsSinceEpoch,
      });
    }
  }

  @override
  createTable(Database db) {
    db.execute('''create table $tableName (
    ${TableBase.columnId} integer PRIMARY KEY AUTOINCREMENT NOT NULL,
    $columnName text,
    ${TableBase.columnCreateTime} integer
    )''');
  }
}

class TableMediaAreaMap extends TableBase {
  // 表名
  static final String tableName = 'media_area_map';
  static final String columnAreaId = "area_id";
  static final String columnMediaId = "media_id";

  @override
  createTable(Database db) {
    db.execute('''create table $tableName (
    ${TableBase.columnId} integer PRIMARY KEY AUTOINCREMENT NOT NULL,
    $columnAreaId integer,
    $columnMediaId integer,
    ${TableBase.columnCreateTime} integer
    )''');
  }
}
